package com.supply.dl.app.http;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.supply.dl.app.AppConfig;
import com.supply.dl.bean.LoginResponse;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.NetWorkUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * 登录的 Observer对象
 * <p>
 * Author: tian <br>
 * Time: 2018/5/7 13:45
 */
public class LoginObserver implements Observer<LoginResponse> {
    private LoadingDialog loadingDialog;
    private Context context;

    public LoginObserver() {
    }

    public LoginObserver(Context context) {
        this.context = context;
        if (context != null && context instanceof Activity)
            this.loadingDialog = LoadingDialog.newInstance(null);
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        if (context != null) {
            //对于网络的检查,在没有网络的时候,调用onFailed方法,并且切断与上游的联系
            if (!NetWorkUtils.isNetworkConnected(context.getApplicationContext())) {
                Toast.makeText(context.getApplicationContext(), "网络出现问题", Toast.LENGTH_SHORT).show();
                onFailure(AppConfig.NO_NETWORK);
                d.dispose();
                return;
            }

            if (context instanceof Activity)
                loadingDialog.show(context);
        }
    }


    @Override
    public void onNext(@NonNull LoginResponse bb) {
        if (loadingDialog != null)
            loadingDialog.dismiss();

        if (bb.getStatus() == -1) {
            String msg = bb.getError();
            onFailure(msg);
            return;
        }

        onSuccess(bb);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        Log.i("gtx_ok_error", DateUtils.getCurrentTime() + " " + e.getMessage());
        if (loadingDialog != null)
            loadingDialog.dismiss();

        if (context != null && !(e instanceof ConnectException) && !(e instanceof SocketTimeoutException))
            Toast.makeText(context.getApplicationContext(), DateUtils.getCurrentTime() + " " + e.getMessage(), Toast.LENGTH_LONG).show();

        onFailure(AppConfig.NO_NETWORK);
    }

    @Override
    public void onComplete() {
    }

    protected void onSuccess(LoginResponse t) {
    }

    protected void onFailure(String msg) {
    }

}
